<template>
  <!-- 编辑当前方案 -->
  <div class="container">
    <section class="aliyun-topbar" style="padding: 25px 100px;">
      <section class="aliyun-topbar-header">
        <section class="aliyun-topbar-element aliyun-logo">
          <!-- <a href class="aliyun-logo-link">
            <span class="topbar-logo-size-cn topbar-logo-new-cn"></span>
          </a>-->
          <router-link to="/">
            <img src="@/assets/logo.png" alt />
          </router-link>
        </section>
      </section>
    </section>
    <div class="title">Edit Solution</div>
    <div class="tabBox">
      <a-tabs default-active-key="1" class="tab" size="large" style>
        <!-- 概述页 -->
        <a-tab-pane key="1" tab="Solution overview">
          <a-form
            :form="form"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }"
            @submit="handleSubmit"
          >
            <!-- <a-form-item label="DepartMent">
              <a-input v-model="Department" disabled />
            </a-form-item>
            <a-form-item label="Class">
              <a-input v-model="Class" disabled />
            </a-form-item>-->
            <a-form-item label="Sector">
              <a-select @select="sectorChange" v-model="Sector">
                <a-select-option
                  v-for="(item, index) in SelectInfo"
                  :key="index"
                  :value="item.sector"
                >{{ item.sector }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="Workcell">
              <a-select @change="WorkcellChange" v-model="workcellName">
                <a-select-option
                  v-for="(item, index) in WorkcellNameInfo"
                  :key="index"
                  :value="item.workcellName"
                >{{ item.workcellName }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="Division">
              <a-select @select="DivisionChange" v-model="Division">
                <a-select-option
                  :value="item.customer"
                  v-for="(item, index) in DivsionInfo"
                  :key="index"
                >{{ item.customer }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="Solution Name">
              <a-input v-model="SolutionName" />
            </a-form-item>
            <a-form-item label="Second Title">
              <a-input v-model="SecondTitle " />
            </a-form-item>
            <a-form-item label="Image">
              <imgUpload @uploadFileList="uploadFileList" model="overviewImg" :imageArr="ImageArr"></imgUpload>
            </a-form-item>
            <a-form-item label="Summary">
              <!-- 纯文本 -->
              <a-textarea
                placeholder
                allow-clear
                v-model="Summary"
                :auto-size="{ minRows: 5, maxRows: 20 }"
              />
            </a-form-item>
            <a-form-item label="Detail">
              <!-- 富文本 -->
              <Editor @schemeDetail="getDetailText" :value="DetailedInformation"></Editor>
            </a-form-item>
            <a-form-item label="SME">
              <SemUpload @getUserList="getUserList"></SemUpload>
            </a-form-item>
            <a-form-item label="Video">
              <VideoUpload
                @uploadFileList="uploadFileList"
                model="overviewVideo"
                :videoUrl="VideoUrl"
                :videoArr="videoList"
              ></VideoUpload>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <!-- 详情页 -->
        <a-tab-pane key="2" tab="Solution Detail" force-render>
          <div class="modelList">
            <div>
              <a-button type="primary" @click="AddMoudule" class="AddModule">AddModule</a-button>

              <a-table :data-source="SchemeInfo.shpSchemeKind" :customRow="clickKindTable ">
                <a-table-column key="KindName" title="KindName" data-index="KindName" />
                <a-table-column key="action" title="Action">
                  <template slot-scope="text, record">
                    <span>
                      <!-- <a-icon
                        type="edit"
                        theme="twoTone"
                        class="iconBtn"
                        @click="editMoudule(text,record)"
                      />-->
                      <a-icon
                        type="delete"
                        theme="twoTone"
                        class="iconBtn"
                        @click="delMoudule(text,record)"
                      />
                      <a-icon
                        type="plus-circle"
                        theme="twoTone"
                        class="iconBtn"
                        @click="addMouduleModal(text,record)"
                      />
                    </span>
                  </template>
                </a-table-column>
              </a-table>
            </div>
            <!-- 元器件信息 -->
            <div class="rt">
              <a-button type="primary" @click="AddComponents" class="AddComponents">AddComponents</a-button>
              <a-table :data-source="singleMoudleInfo" :customRow="rowClick">
                <a-table-column key="ProductName" title="ProductName" data-index="ProductName" />

                <a-table-column
                  key="ProductParameter"
                  title="ProductParameter"
                  data-index="ProductParameter"
                >
                  <template slot-scope="text,record">
                    <div v-html=" text"></div>
                  </template>
                </a-table-column>
                <a-table-column key="quantity" title="Quantity" data-index="Quantity">
                  <template>
                    <div>{{ Quantity }}</div>
                  </template>
                </a-table-column>
                <a-table-column key="UnitName" title="Unit" data-index="UnitName" />
                <!-- TemplatePictrue 图片路径 -->
                <a-table-column key="Imgs" title="Imgs" :data-index="Imgs">
                  <template slot-scope="text,record">
                    <!-- viewer插件接收list -->
                    <viewer style="width: 150px;height: 150px; overflow: hidden;">
                      <div
                        v-for="(item, index) in record.Imgs"
                        :key="index"
                        style="width:150px;height:150px;"
                      >
                        <img :src="item" style="width:150px;height:150px;" />
                      </div>
                    </viewer>
                  </template>
                </a-table-column>

                <a-table-column key="Price" title="Price" data-index="Price" />
                <a-table-column key="Actions" title="Actions">
                  <template slot-scope="text,record">
                    <div>
                      <!-- <a-icon
                        type="edit"
                        theme="twoTone"
                        class="iconBtn"
                        @click="editGoods(text,record)"
                      />-->
                      <a-icon
                        type="delete"
                        theme="twoTone"
                        class="iconBtn"
                        @click="delGoods(text,record)"
                      />
                    </div>
                  </template>
                </a-table-column>
              </a-table>
            </div>
          </div>
          <!-- 小计总计区域 -->
          <!-- <div>
            <a-form-item label class="totalPriceBox">
              <a-icon type="dollar" theme="twoTone" />
              <span>Extensions</span>
              <span>{{ subPrice }}</span>
              <a-icon type="dollar" theme="twoTone" />
              <span>Footings</span>
              <span>{{ totalPrice }}</span>
            </a-form-item>
          </div>-->
        </a-tab-pane>
      </a-tabs>
    </div>
    <div class="btnBox">
      <a-button type="primary" class="submitBtn" @click="submitAll">Submit</a-button>
      <a-button type="primary" class="submitBtn" @click="closeEdit">Back</a-button>
    </div>
    <!-- 编辑新增元器件弹窗 -->
    <a-modal v-model="visible" title="AddComponents" @ok="handleOk">
      <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="ProductName">
          <a-input v-model="ProductName" />
        </a-form-model-item>
        <a-form-model-item label="Parammeter ">
          <a-textarea v-model="ProductParameter" allow-clear />
        </a-form-model-item>
        <a-form-model-item label=" Number ">
          <a-input-number v-model="Quantity" />
        </a-form-model-item>
        <a-form-model-item label="Unit  ">
          <a-input v-model="UnitName" />
        </a-form-model-item>
        <a-form-model-item label="Price($) ">
          <a-input v-model="Price" prefix="$" suffix="dollar" />
        </a-form-model-item>
        <a-form-model-item label="Image">
          <div :key="ImgKey">
            <imgUpload
              @uploadFileList="uploadFileList"
              model="moudleImg"
              :isOpen="isOpen"
              :file="fileList"
            ></imgUpload>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 新增Moudel模组 -->
    <a-modal v-model="moudelVisible" title="Add Module" @ok="openModuleOk()">
      <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="ModuleName">
          <a-input v-model="ModuleName" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import imgUpload from '@/components/upload/imgUpload'
import Editor from '@/components/Editor/commonWangEditor'
import VideoUpload from '@/components/upload/videoUpload'
import Header from '@/components/layout/header'
import SemUpload from '@/pageModule/SEM/SmeEdit'

export default {
  name: 'EditScheme',
  data() {
    return {
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      loading: true,
      loadingMore: false,
      showLoadingMore: true,
      data: [],
      componentData: [],
      visible: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 16 }, //表单布局配置
      selectedRowKeys: [], // Check here to configure the default column
      subPrice: 0,
      totalPrice: 0,
      SelectInfo: [],
      SectorInfo: [],
      WorkcellNameInfo: [],
      DivsionInfo: [],
      // 方案概述
      Department: '',
      Class: '',
      theSector: '',
      theWorkCell: '',
      theDivison: '',
      SolutionName: '',
      SecondTitle: '',
      ImageList: [],
      Summary: '',
      Detail: '',
      DetailedInformation: '',
      VideoUrl: '',
      ImageArr: [],
      Sector: '',
      videoList: [],
      // 方案详情
      SectorList: [],
      ProductName: '',
      Price: '',
      goodsImgList: [],
      KindId: '',
      Quantity: '',
      UnitName: '',
      URL: [],
      Moudeldata: [],
      moudelVisible: false,
      ModuleName: '',
      ProductParameter: '',
      lastParameter: '',
      doType: '',
      ModuleTipIndex: '',
      MoudelList: [],
      SchemeInfo: {},
      singleMoudleInfo: [], //单个模组数据
      clickIndex: 0,
      Imgs: [],
      isOpen: '',
      ImgKey: '',
      theSchemeId: '',
      Division: '',
      workcellName: '',
      fileList: [],
      UserList: [],
    }
  },
  components: {
    Header,
    imgUpload,
    Editor,
    VideoUpload,
    SemUpload,
  },
  props: ['SchemeId'],
  watch: {
    visible() {
      if (this.visible) {
        this.ImgKey = ''
      } else {
        this.ImgKey = Math.random()
      }
      console.log('this.ImgKey :>> ', this.ImgKey)
    },
    ProductParameter() {
      this.lastParameter = this.ProductParameter.replace(/\r\n/g, '<br>')
        .replace(/\n/g, '<br>')
        .replace(/\s/g, ' ') //转换格式
      console.log(this.lastParameter, 'lastParameter')
    },
    Price() {},
    Quantity() {
      if (this.Quantity < 0) {
        this.Quantity = 0
      }
    },
    Sector() {
      this.theSector = this.Sector
    },
    theSchemeId() {
      sessionStorage.setItem('schemeId', this.theSchemeId)
      if (!this.theSchemeId) {
        this.theSchemeId = sessionStorage.getItem('schemeId')
      }
    },
    videoList() {
      console.log('this.videoList :>> ', this.videoList)
    },
  },
  created() {
    this.theSchemeId = this.SchemeId
    this.getRouterData()
    this.getSchemeInfo()
  },

  mounted() {
    this.getSelectInfo()
  },
  methods: {
    initSeotor() {},
    getUserList(e) {
      console.log('父组件 UserList:>> ', e)
      if (e.length > 0) {
        this.UserList = e
      }
    },
    closeEdit() {
      this.$emit('editStatus', false)
    },
    // 点击模块表 单行
    clickKindTable(record, index) {
      return {
        on: {
          click: () => {
            this.getSchemeInfo()
            console.log(record, index, '点击大表')
            this.KindId = record.KindId
            index = Number(index)
            this.singleMoudleInfo = this.SchemeInfo.shpSchemeKind[
              index
            ].shpSchemeDetailed
            this.clickIndex = index
            console.log('this.clickIndex :>> ', this.clickIndex)
            console.log('元器件', this.singleMoudleInfo)
          },
        },
      }
      console.log(record, index, 'kindClick')
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
        }
      })
    },
    MoudelTableChange(e) {},
    // 生成本页面唯一的方案id
    getUniqueId(randomLength) {
      return Number(
        Math.random().toString().substr(3, randomLength) + Date.now()
      ).toString(36)
    },
    // 查询本页面唯一id的方案详情
    getSchemeInfo() {
      const a = {
        method: 'ShpSchemeDetailed_Que',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        language: 1,
        datas: {
          SchemeId: this.theSchemeId,
        },
      }
      if (!this.theSchemeId) {
        console.log('this.SchmeId :>> ', this.theSchemeId)
        return
      }
      this.$post(a).then((result) => {
        console.log(result, ' 当前方案', this.clickIndex)
        this.$nextTick(() => {
          this.SchemeInfo = result.data
          this.Division = result.data.Division
          this.ImageArr = eval('(' + result.data.Image + ')')

          this.Sector = result.data.Sector
          this.SectorList[0] = result.data.Sector
          this.DivsionInfo[0] = result.data.Division
          this.WorkcellNameInfo[0] = result.data.Workcell
          this.SolutionName = result.data.SolutionName
          this.SecondTitle = result.data.SecondTitle
          this.workcellName = result.data.Workcell
          this.Summary = result.data.Summary
          this.DetailedInformation = result.data.DetailedInformation
          this.VideoUrl = result.data.Video
          this.videoList[0] = result.data.Video
          if (result.data.shpSchemeKind[this.clickIndex].shpSchemeDetailed) {
            result.data.shpSchemeKind[this.clickIndex].shpSchemeDetailed.map(
              (item) => {
                item.Imgs = eval('(' + item.Imgs + ')')
                return item
              }
            )
          } else {
            result.data.shpSchemeKind[this.clickIndex].shpSchemeDetailed = []
          }

          // console.log(
          //   result.data.shpSchemeKind[this.clickIndex].shpSchemeDetailed,
          //   'shpSchemeDetailed'
          // )
          this.singleMoudleInfo =
            result.data.shpSchemeKind[this.clickIndex].shpSchemeDetailed
        })
      })
    },
    /*模组
     */
    openModuleOk(type) {
      // 新增Moudel模组
      if (!this.ModuleName) {
        return
      }
      if (this.doType === 'add') {
        this.AddMouduleInfo()
      }
      if (this.doType == 'edit') {
        // this.Moudeldata[this.ModuleTipIndex] = this.ModuleName
      }
      this.moudelVisible = false
    },
    //添加，模组
    addMouduleModal(record, text) {
      this.AddComponents()
      console.log(record, text, '模组')
    },
    AddMoudule() {
      this.moudelVisible = true
      this.doType = 'add'
      this.ModuleName = ''
    },
    AddMouduleInfo() {
      const KindId = this.getUniqueId(10)
      console.log('没有方案id ', this.theSchemeId)

      if (!this.theSchemeId) {
        console.log('没有方案id ', this.theSchemeId)
        return
      }
      const a = {
        method: 'ShpSchemeKind_Add',
        userId: window.userId || 1,
        sign: 'A0251DD654CBB418AF1422CA880A1270',
        currentPage: 0,
        limit: 0,
        language: 0,
        datas: {
          SchemeId: this.theSchemeId,
          KindId: KindId,
          KindName: this.ModuleName,
        },
      }

      this.MoudelList.push({
        SchemeId: this.theSchemeId,
        KindId: KindId,
        KindName: this.ModuleName,
      })
      // this.$post(a).then((result) => {
      //   this.getSchemeInfo()
      // })
    },
    // 编辑模组
    editMoudule(item, index) {
      this.moudelVisible = true
      this.doType = 'edit'
      this.ModuleTipIndex = index
      console.log('item :>> ', item)
    },
    //删除模组
    delMoudule(item, index) {
      console.log(item, 'del')
      this.doType = 'del'
      const that = this
      const a = {
        method: 'ShpSchemeKind_Del',
        userId: window.userId || 1,
        sign: 'A0251DD654CBB418AF1422CA880A1270',
        currentPage: 0,
        limit: 0,
        language: 0,
        datas: {
          SchemeId: item.theSchemeId,
          KindId: item.KindId,
        },
      }
      this.$post(a).then((result) => {
        if (result.code == 0) {
          this.$message.success('successfully delete!')
          this.getSchemeInfo()
        }
      })
    },
    // 添加元器件
    AddComponents() {
      // 清空数据
      this.ProductName = ''
      this.Quantity = ''
      this.ProductParameter = ''
      this.lastParameter = ''
      this.UnitName = ''
      this.Price = ''
      this.fileList = []
      this.Imgs = []
      // 校验
      if (this.KindId) {
        this.visible = true
        this.isOpen = true
      } else {
        this.$message.warning('Please select or create a new module to edit!')
      }
    },
    // 删除元器件明细
    delSchemeDetailed(item) {
      console.log('item :>> ', item)
      const a = {
        method: 'ShpSchemeDetailed_Del',
        userId: window.userId || 1,
        sign: 'A0251DD654CBB418AF1422CA880A1270',
        currentPage: 0,
        limit: 0,
        language: 0,
        datas: {
          SchemeId: item.SchemeId,
          KindId: item.KindId,
          ProductName: item.ProductName,
        },
      }
      this.$post(a).then((result) => {
        if (result.code === 0) {
          console.log(result, '删除方案明细完成')
          this.$message.success('Deleted successfully!')
          this.getSchemeInfo() //刷新表格
        }
      })
    },
    getRouterData() {},

    sectorChange(value, e) {
      // 选择select
      const key = Number(e.key)
      const info = this.SelectInfo[key].workcellName
      this.WorkcellNameInfo = info
      this.theSector = value
    },
    WorkcellChange(value, e) {
      this.workcellName = value
      const key = Number(e.key)
      this.DivsionInfo = this.WorkcellNameInfo[key].customer
    },
    DivisionChange(value, e) {
      this.Division = value
    },
    // 弹窗
    showModal() {
      this.visible = true
      this.isOpen = true
    },
    // 单个模块 元器件信息修改
    handleOk(e) {
      // 校验
      if (/\D/.test(this.Price)) {
        this.$message.error('Please enter the correct amount!')
        this.Price = ''
        return
      } else if (!this.ProductName) {
        this.$message.error('Please enter the ProductName!')
        return
      }
      if (this.lastParameter) {
        this.lastParameter = '<p>' + this.lastParameter + '</p>'
      }
      const a = {
        method: 'ShpSchemeDetailed_Add',
        userId: window.userId || 1,
        sign: 'A0251DD654CBB418AF1422CA880A1270',
        currentPage: 0,
        limit: 0,
        language: window.language || 1,
        datas: {
          SchemeId: this.theSchemeId,
          KindId: this.KindId,
          ProductName: this.ProductName,
          ProductParameter: this.lastParameter,
          Quantity: this.Quantity,
          UnitName: this.UnitName,
          Imgs: this.Imgs,
          Price: this.Price,
        },
      }
      // this.visible = false
      this.$post(a).then((result) => {
        console.log(result)

        if (result.code === 0) {
          this.$message.success('submit successfully!')
          this.getSchemeInfo()
          this.visible = false
          this.isOpen = true
        }
      })
    },
    // 删除元器件
    delGoods(item, index) {
      console.log(item, index)
      const ProductName = item.ProductName
      this.delSchemeDetailed(item)
    },
    editGoods(item, index) {
      this.visible = true
      this.isOpen = true
    },
    // 删除方案
    delScheme() {
      const a = {
        method: 'ShpScheme_Del',
        userId: window.userId || 1,
        sign: 'A0251DD654CBB418AF1422CA880A1270',
        currentPage: 0,
        limit: 0,
        language: window.language || 1,
        datas: {
          SchemeId: this.theSchemeId,
        },
      }
      this.$post(a).then((result) => {
        result = eval('(' + result + ')')
      })
    },

    addSchemeInstro() {
      const Summary = this.Summary.replace(/\r\n/g, '<br>')
        .replace(/\n/g, '<br>')
        .replace(/\s/g, ' ') //转换格式

      const b = {
        method: 'ShpScheme_Add',
        userId: window.userId || 1,
        sign: 'A0251DD654CBB418AF1422CA880A1270',
        currentPage: 0,
        limit: 0,
        language: window.language || 1,
        datas: {
          SchemeId: this.theSchemeId,
          ModuleId: this.ModuleId,
          SubId: this.SubId,
          Sector: this.theSector,
          Workcell: this.workcellName,
          Division: this.Division,
          SchemeType: this.SchemeType,
          SolutionName: this.SolutionName,
          SecondTitle: this.SecondTitle,
          Image: this.ImageList,
          Summary: Summary,
          DetailedInformation: this.DetailedInformation.toString(),
          Video: this.VideoUrl,
          PDFAddress: this.PDFAddress,
          UserList: this.UserList,
        },
      }
      let arr1, arr2

      this.$post(b).then((result) => {
        console.log(result)
        arr2 = result
        if (result.code == 0) {
          this.$message.success('successfully Change!')
        }
      })
      this.ImageList = []
      return arr1, arr2
    },
    onSelectChange(selectedRowKeys, selectedRows) {},
    rowClick(e) {},
    submitAll() {
      if (!this.theSector || !this.workcellName || !this.Division) {
        this.$message.warning(
          'Please select sector, workcell and division first!'
        )
        return
      } else if (!this.SolutionName || !this.SecondTitle) {
        this.$message.warning('Please enter solutionname, secondtitle first!')
        return
      }

      const info = this.addSchemeInstro()
    },
    getSelectInfo() {
      // 获取select数据
      const p = {
        method: 'tb2_workcell_customer_Que',
        userId: window.userId || 1,
        sign: 'A0251DD654CBB418AF1422CA880A1270',
        currentPage: 0,
        limit: 0,
        language: window.language || 1,
        fieldList: '',
        datas: {},
      }

      this.$post(p).then((result) => {
        this.SelectInfo = result.data
      })
    },
    getDetailText(e) {
      // 获取方案Detail 富文本
      if (e) this.DetailedInformation = e
    },
    uploadFileList(e) {
      const model = e.model
      const fileList = e.fileList
      const isAllowUpload = e.isAllowUpload
      this.ImageList = []
      this.Imgs = []
      if (fileList) {
        if (model === 'overviewImg') {
          fileList.map((item) => {
            this.ImageList.push(item.response.data.fileName)
          })
        } else if (model === 'moudleImg') {
          fileList.map((item) => {
            this.Imgs.push(item.response.data.fileName)
          })
        } else if (model === 'overviewVideo') {
          this.VideoUrl = e.file.response.data.fileName
        }
        console.log('this.ImageList :>> ', this.ImageList)
      }
    },
  },
}
</script>

<style lang="less" scoped>
@import url('css/addProject.less');
.rowSelect {
  background-color: #cbf2ff;
}
</style>